package com.study.factory;

import com.study.service.IAccountService;
import com.study.utils.TransactionUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ServiceFactory {
    private IAccountService accountService;
    private TransactionUtil transactionUtil;

    public void setTransactionUtil(TransactionUtil transactionUtil) {
        this.transactionUtil = transactionUtil;
    }

    public void setAccountService(IAccountService accountService) {
        this.accountService = accountService;
    }

    public IAccountService getAccountService() {
        IAccountService proxy = (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("proxy正在执行....");
                        Object rv = null;
                        try {
                            transactionUtil.beginTransaction();
                            rv = method.invoke(accountService, args);
                            transactionUtil.commitTransaction();
                        } catch (Exception e) {
                            e.printStackTrace();
                            transactionUtil.rollbackTransaction();
                        } finally {
                            transactionUtil.releaseTransaction();
                        }
                        return rv;
                    }
                });
        return proxy;
    }
}
